import {Navigate, Outlet, useLocation, useNavigate, useRoutes} from "react-router-dom";
import {isEmpty} from "@/utils/common.ts";
import {getRoutersUrl, getUserInfoUrl} from "@/api/system/user.ts";
import {setUserInfo} from "@/store/modules/userSlice.ts";
import {constantRoutes, createMenus, createRouters, createTagViews, dynamicRouter} from "@/router";
import {setDefinedRouter, setRouters} from "@/store/modules/routerSlice.ts";
import React, {Suspense, useEffect, useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import {globalMessageApi} from "@/components/OpComponent/Message";


function RouterBeforeEach(props: any) {
    const {children} = props

    return children
}


/*
* 路由守卫组件
* */
export default function AuthRouter({children}: any) {
    const whiteList = ['/login', '/qrCodeLogin', '/text']
    const location = useLocation()
    const {token, userInfo} = useSelector((state: any) => state.user)
    const dispatch = useDispatch()
    const navigator = useNavigate()

    const localRouter = [...constantRoutes, ...dynamicRouter]

    // 需要注入的路由表信息
    const [routerList, setRouterList] = useState<any>([...createRouters(localRouter)])
    const elements = useRoutes(routerList)

    function checkLogin() {
        const isLogin = !!token
        if (!isLogin) {
            // 未登录 在白名单中，放行
            if (whiteList.includes(location.pathname)) return;
            globalMessageApi.warning("未登录, 请先登录!")
            // 跳转到登录页
            navigator("/login")
        } else {
            // 已经登录了， 获取自己的信息，获取路由表信息
            console.log("已经登录了", userInfo)
            if (isEmpty(userInfo)) {
                // 获取当前登录用户信息，再获取路由表信息
                console.log("获取当前登录用户信息，再获取路由表信息")
                getUserInfoUrl().then((res: any) => {
                    dispatch(setUserInfo(res.user))
                    getRoutersUrl().then((res: any) => {
                        const _routerList = createRouters([...localRouter, ...res.data])
                        dispatch(setDefinedRouter(res.data))
                        dispatch(setRouters(createTagViews([...localRouter, ...res.data])))
                        setRouterList([..._routerList])
                        console.log("最后生成的路由 routerL ist", _routerList)
                    })
                }).catch((err: any) => {
                    console.log("获取路由信息失败", err)
                })
            }
        }
    }

    useEffect(() => {
        checkLogin()
    }, [location]);

    return <RouterBeforeEach>
        {elements}
    </RouterBeforeEach>
}
